<?php
namespace app\validators;

use app\models\SmsLog;
use yii\validators\Validator;

/**
 * 短信验证码验证器
 * Class SmscodeValidator
 */
class SmscodeValidator extends Validator
{
	/**
   * 对应Smslog表中的dowhat字段，用来匹配不同用途的验证码
	 * @var string sms code type
	 */
	public $dowhat;
	/**
	 * Model或者form中提交的手机号字段名称
	 * @var string
	 */
	public $phoneAttribute = 'phone';
	/**
	 * 验证码过期时间
	 * @var int
	 */
	public $expireTime = 10800;

  /**
	 * @param \yii\base\Model $model
	 * @param string $attribute
	 */
	public function validateAttribute($model, $attribute)
	{
		$fieldName = $this->phoneAttribute;
		$phone = $model->$fieldName;

		$smsLog = SmsLog::find()->where([
			'phone' => $phone,
			'dowhat' => "userRegister",
			/*'used'=>0,*/
		])->orderBy('create_time DESC')->one();
		if(is_null($smsLog)){
			$this->addError($model, $attribute,'短信验证码错误');
			return;
		}

		/** @var $smsLog SmsLog */
		$time = time();
		$create_time=strtotime($smsLog->create_time);
		if(
			is_null($smsLog) ||
			($smsLog->code != $model->$attribute)
		){
			$this->addError($model, $attribute,'短信验证码错误');
		}else if($create_time > $time){
			$this->addError($model, $attribute,'短信验证码发送时间异常，请重新发送');
		}
		else if($time > ($create_time + $this->expireTime) )
		{
			$this->addError($model, $attribute,'短信验证码已失效，请重新发送');
		}else{
			$smsLog->used = 1;
			$smsLog->use_time = $time;
			$smsLog->save();
		}
	}

}
